package com.autguigu.gulimall.ssoserver.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @GetMapping("/userinfo")
    @ResponseBody
    public String userInfo(@RequestParam("token") String token) {
        // 根据请求地址中携带的令牌去redis中查询用户信息
        String str = stringRedisTemplate.opsForValue().get(token);
        return str;
    }





    @GetMapping("login.html")
    public String loginPage(@RequestParam(value = "redirect_url", required = false) String url, Model model,
                            @CookieValue(value = "sso_token", required = false) String sso_token) {
        if(!StringUtils.isEmpty(sso_token)){
            // 说明之前有人登录过sso，令牌信息存在，直接根据请求地址中的重定向地址直接跳转回去，并将令牌信息以地址参数的方式返回给请求方
            return "redirect:" + url + "?token=" + sso_token;
        }
        // 没有令牌信息，跳转到登录页面进行登录
        model.addAttribute("url", url);
        return "login";
    }

    /**
     * 处理用户登录请求
     * @param username
     * @param password
     * @param url
     * @param response
     * @return
     */
    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          @RequestParam("url") String url,
                          HttpServletResponse response) {
        if (!StringUtils.isEmpty(username) && !StringUtils.isEmpty(password)) {
            // 登录成功 用户信息放到redis中
            String replace = UUID.randomUUID().toString().replace("_", "");
            stringRedisTemplate.opsForValue().set(replace,username);

            // 给sso游览器留下一个cookie信息
            Cookie cookie = new Cookie("sso_token",replace);
            response.addCookie(cookie);
            return "redirect:" + url + "?token=" + replace;
        }
        return "login";
    }


}
